package net.avcompris.binding.impl;

import static com.avcompris.util.ExceptionUtils.nonNullArgument;
import static org.apache.commons.lang3.CharEncoding.UTF_8;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public abstract class AbstractToFileSerializer<T> extends AbstractSerializer<T> {

	protected AbstractToFileSerializer(final File file) {

		this.file = nonNullArgument(file, "file");
	}

	private final File file;

	@Override
	public final void serialize(final T node) throws IOException {

		nonNullArgument(node, "node");

		final OutputStream os = new FileOutputStream(file);
		try {

			final Writer writer = new OutputStreamWriter(os, UTF_8);

			final AbstractToWriterSerializer<T> serializer = createToWriterSerializer(writer);

			serializer.serialize(node);

			writer.flush();

		} finally {
			os.close();
		}
	}

	protected abstract AbstractToWriterSerializer<T> createToWriterSerializer(
			Writer writer);
}
